#!/usr/bin/env bash

APP=wine
SITE="mmtrt/WINE_AppImage"

# CREATE DIRECTORIES
if [ -z "$APP" ]; then exit 1; fi
mkdir -p "/opt/$APP/tmp" && cd "/opt/$APP/tmp" || exit 1

# ADD THE REMOVER
echo "#!/bin/sh
rm -f /usr/local/share/applications/AM-$APP.desktop /usr/local/bin/$APP /usr/local/bin/wine64
rm -R -f /opt/$APP" > "/opt/$APP/remove"
chmod a+x "/opt/$APP/remove"

# DOWNLOAD AND PREPARE THE APP
# $version is also used for updates

printf "%s\n" "$(curl -Ls https://api.github.com/repos/"$SITE"/releases \
	| grep browser_download_url | cut -d '"' -f 4)" | tr ' ' '\n' | grep -i appimage | grep -v zsync >> ./wine-args
printf "Select a URL from this menu (read carefully) or press CTRL+C to abort:\n-----------------------------------------------------------------------\n"; sleep 1;
	select version in $(cat ./wine-args | sort -u | uniq); do test -n "$version" && break; echo ">>> Invalid Selection"; done
wget "$version"
wget "$version.zsync" 2> /dev/null
echo "$version" >> /opt/$APP/version
# Use tar fx ./*tar* for example in this line in case a compressed file is downloaded.
cd ..
mv ./tmp/*mage ./"$APP"
mv ./tmp/*.zsync ./"$APP".zsync 2> /dev/null
chmod a+x "/opt/$APP/$APP"
rm -R -f ./tmp

# LINK
ln -s "/opt/$APP/$APP" "/usr/local/bin/$APP"
ln -s "/usr/local/bin/$APP" "/usr/local/bin/wine64"

# SCRIPT TO UPDATE THE PROGRAM
cat >> "/opt/$APP/AM-updater" << 'EOF'
#!/bin/sh
APP=wine
SITE="mmtrt/WINE_AppImage"
if [ -z "$APP" ]; then exit 1; fi
version0=$(cat "/opt/$APP/version")
tag=$(echo "$version0" | tr '/' '\n' | tail -2 | head -1)
version=$(curl -Ls https://api.github.com/repos/mmtrt/WINE_AppImage/releases | grep browser_download_url | grep -i "download/$tag/$app" | grep -i appimage | cut -d '"' -f 4 | head -1)
mkdir "/opt/$APP/tmp"
cd "/opt/$APP/tmp" || exit 1
wget "$version.zsync" 2> /dev/null
cd ..
mv ./tmp/*.zsync ./"$APP".zsync
rm -R -f ./tmp
zsync "/opt/$APP/$APP.zsync"
rm -R -f "/opt/$APP/*zs-old" "/opt/$APP/*.part"
chmod a+x "/opt/$APP/$APP"
if [ "$version" != "$version0" ]; then
	echo "$version" > /opt/$APP/version
fi
EOF
chmod a+x "/opt/$APP/AM-updater"
